package com.kuolie.answer.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import sun.misc.BASE64Encoder;

import javax.net.ssl.HttpsURLConnection;
import java.io.*;
import java.net.URL;
import java.util.*;

/**
 * 获取微信APPID和secret工具类
 */

public  class AccessTokenUtil {

    public synchronized static String getAccessToken() {
        String FileName = "WxTokenUtil.properties";
        try {
            Properties prop = new Properties();// 属性集合对象
            InputStream fis = AccessTokenUtil.class.getClassLoader().getResourceAsStream(FileName);
            prop.load(fis);// 将属性文件流装载到Properties对象中  
            fis.close();// 关闭流  
            String APPID = prop.getProperty("APPID");
            String APPSECRET = prop.getProperty("APPSECRET");
            String access_token = prop.getProperty("access_token");
            String expires_in = prop.getProperty("expires_in");
            String last_time = prop.getProperty("last_time");
            int int_expires_in = 0;
            long long_last_time = 0;
            try {
                int_expires_in = Integer.parseInt(expires_in);
                long_last_time = Long.parseLong(last_time);
            } catch (Exception e) {

            }
            long current_time = System.currentTimeMillis();

            if ((current_time - long_last_time) / 1000 >= int_expires_in) {
                String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
                        + APPID + "&secret=" + APPSECRET;
                JSONObject jobject = httpRequest(url);
                String  j_access_token = (String) jobject.get("access_token");
                String  j_expires_in = jobject.get("expires_in").toString();
                if (j_access_token != null && j_expires_in != null) {
                    prop.setProperty("access_token", j_access_token);
                    prop.setProperty("expires_in", j_expires_in);
                    prop.setProperty("last_time", System.currentTimeMillis() + "");
                    URL url_ = AccessTokenUtil.class.getClassLoader().getResource(FileName);
                    FileOutputStream fos = new FileOutputStream(new File(url_.toURI()));
                    prop.store(fos, null);
                    fos.close();// 关闭流  
                }
                return j_access_token;
            } else {
                return access_token;
            }
        } catch (Exception e) {
            return null;
        }
    }

    public synchronized static JSONObject httpRequest(String requestUrl) {
        JSONObject jsonObject = null;
        StringBuffer buffer = new StringBuffer();
        try {

            URL url = new URL(requestUrl);
            HttpsURLConnection httpUrlConn = (HttpsURLConnection) url
                    .openConnection();
            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);
            httpUrlConn.setRequestMethod("GET");
            httpUrlConn.connect();
            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(
                    inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(
                    inputStreamReader);
            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();
            inputStream = null;
            httpUrlConn.disconnect();
            jsonObject = JSONObject.parseObject(buffer.toString());

        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonObject;
    }
    public  static String httpRequestPost(String url,String access_token ,String scene,String page) {
        JSONObject jobject = new JSONObject();
        JSONObject jo = null;
        jobject.put("scene", scene);
        jobject.put("path", page);
        jobject.put("width", 430);
        jobject.put("auto_color", false);
        Map<String, Object> line_color = new HashMap<>();
        line_color.put("r", 0);
        line_color.put("g", 0);
        line_color.put("b", 0);
        jobject.put("line_color", line_color);
        InputStream is = AccessTokenUtil.doPost(url, jobject);
        boolean result = true;
        if (BL3Utils.isEmpty(is)) {
            result = false;
        };
        String str = inputToBase644(is);
        if(result){
            return str;
        }
        return null;
    }
    private static String inputToBase644(InputStream in){
        BASE64Encoder encoder = new BASE64Encoder();
        byte[] data = null;
        List<Integer> list = new ArrayList<Integer>();
        int x = 0;
        try {
            while (x!=-1){
                int b = in.read();
                x=b;
                list.add(b);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        data = new byte[list.size()];
        int i = 0;
        for (int b :list){
            data[i] = (byte)b;
            i++;
        }
        String  s = encoder.encode(data);
        return s;
    }
    private static InputStream doPost(String url, JSONObject jsonParam) {
        InputStream instreams = null;
        HttpPost httpRequst = new HttpPost(url);// 创建HttpPost对象
        try {
            StringEntity se = new StringEntity(jsonParam.toString(),"utf-8");
            se.setContentType("application/json");
            se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"UTF-8"));
            httpRequst.setEntity(se);
            HttpResponse httpResponse = new DefaultHttpClient().execute(httpRequst);
            if (httpResponse.getStatusLine().getStatusCode() == 200) {
                HttpEntity httpEntity = httpResponse.getEntity();
                if (httpEntity != null) {
                    instreams = httpEntity.getContent();
                }
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return instreams;
    }
}  